﻿using System;
using System.Collections.Generic;
using System.Text;
using Brc_PaaS.Common.Helper;
using Brc_PaaS.Common.Model.Basic;
using Brc_PaaS.Common.Model.Exceptionless;
using Exceptionless;
using Exceptionless.Logging;
using Microsoft.Extensions.Configuration;

namespace Brc_PaaS.Core.Exceptionless
{
    public class LogManager : ILogManager
    {
        private LogModel _logConfig;
        private Dictionary<string, string> _authDic;

       

        public LogManager()
        {

        }
        public LogModel LogConfig { get { return _logConfig; } set { _logConfig = value; } }

        public Dictionary<string, string> AuthDic => GetAuthDic();

        private Dictionary<string, string> GetAuthDic()
        {
            if (_logConfig == null)
                return null;
            _authDic = new Dictionary<string, string>() { { "Authorization", $"Bearer {_logConfig.Token}" } };
            return _authDic;
        }
        /// <summary>
        /// 创建APIKEY
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResponseModel<EplCreateApiKeyResModel> CreateApiKeyForBusinessSystemInExceptionless(EplCreateApiKeyReqModel model)
        {
            ResponseModel<EplCreateApiKeyResModel> result = new ResponseModel<EplCreateApiKeyResModel>() { IsSuccess = false, Msg = string.Empty, Data = new EplCreateApiKeyResModel() };
            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version }, { "ProjectId", model.project_id } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.CreateTokenApi, uriDic));
            var jsonParam = JsonHelper.SerializeObject(model);
            System.Net.HttpStatusCode code;
            string data = HttpHelper.HttpPostGetCode(apiAddress, out code, jsonParam, AuthDic);
            if (code == System.Net.HttpStatusCode.Created)
            {
                result.IsSuccess = true;
                result.Data = JsonHelper.DeserializeObject<EplCreateApiKeyResModel>(data);
                //utc时间比当前时间少8小时
                result.Data.created_utc = result.Data.created_utc.AddHours(8);

            }
            else
            {
                result.Msg = $"创建APIKEY时出现错误，创建失败。得到反馈代码：{code}";
            }
            return result;
        }

        public ResponseModel<EplCreateProjectResModel> CreateProjectInExceptionless(EplCreateProjectReqModel model)
        {
            ResponseModel<EplCreateProjectResModel> result = new ResponseModel<EplCreateProjectResModel>() { IsSuccess = false, Msg = string.Empty, Data = new EplCreateProjectResModel() };
            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.CreateProjectApi, uriDic));
            var jsonParam = JsonHelper.SerializeObject(model);
            System.Net.HttpStatusCode code;
            string data = HttpHelper.HttpPostGetCode(apiAddress, out code, jsonParam, AuthDic);
            if (code == System.Net.HttpStatusCode.Created)
            {
                result.IsSuccess = true;
                result.Data = JsonHelper.DeserializeObject<EplCreateProjectResModel>(data);
                result.Data.created_utc = result.Data.created_utc.AddHours(8);
            }
            else
            {
                result.Msg = $"创建项目时出现错误，创建失败。得到反馈代码：{code}";
            }
            return result;
        }

        public ResponseModel<EplSearchExceptionDetailModel> GetExceptionDetailFromExceptionless(string exceptionId)
        {
            ResponseModel<EplSearchExceptionDetailModel> result = new ResponseModel<EplSearchExceptionDetailModel>() { IsSuccess = false, Msg = string.Empty, Data = new EplSearchExceptionDetailModel() };

            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version }, { "EventId", exceptionId } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.EventDetailApi, uriDic));

            System.Net.HttpStatusCode code;
            string data = HttpHelper.HttpGetOutCode(apiAddress, out code, AuthDic);
            if (code == System.Net.HttpStatusCode.OK)
            {
                data = data.Replace("@simple_error", "simple_error").Replace("@user", "user");
                result.Data = JsonHelper.DeserializeObject<EplSearchExceptionDetailModel>(data);
                result.IsSuccess = true;
            }
            else
            {
                result.Msg = $"获取异常详细信息时出现错误，获取失败。得到反馈代码：{code}";
            }
            return result;
        }

        public ResponseModel<List<EplSearchEventResModel>> QueryEventInExceptionless(EplSearchEventReqModel model, out int total)
        {
            ResponseModel<List<EplSearchEventResModel>> result = new ResponseModel<List<EplSearchEventResModel>>() { IsSuccess = false, Msg = string.Empty, Data = new List<EplSearchEventResModel>() };

            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version }, { "ProjectId", model.projectid } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.EventsApi, uriDic));
            var countApiAddr = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.EventsCountApi, uriDic));


            System.Net.HttpStatusCode code;
            System.Net.HttpStatusCode countCode;

            var queryString = FmtGetUrl(model);
            apiAddress = apiAddress + queryString;
            countApiAddr = countApiAddr + queryString;

            var count = HttpHelper.HttpGetOutCode(countApiAddr, out countCode, AuthDic);
            if (countCode != System.Net.HttpStatusCode.OK)
            {
                result.Msg = $"查询日志记录总数时出现错误，查询失败。得到反馈代码：{countCode}";
                total = 0;
                return result;
            }
            var countModel = JsonHelper.DeserializeObject<dynamic>(count);
            total = Convert.ToInt32(countModel.total);

            string data = HttpHelper.HttpGetOutCode(apiAddress, out code, AuthDic);
            if (code == System.Net.HttpStatusCode.OK)
            {
                result.Data = JsonHelper.DeserializeObject<List<EplSearchEventResModel>>(data);
                result.IsSuccess = true;
            }
            else
            {
                result.Msg = $"查询日志列表数据时出现错误，查询失败。得到反馈代码：{code}";
            }
            return result;
        }
        private string FmtGetUrl(EplSearchEventReqModel model)
        {
            var sb = new StringBuilder();
            sb.Append(string.Format("?filter=type:{0}", model.type));
            if (!string.IsNullOrEmpty(model.level))
            {
                sb.Append(string.Format("+level:{0}", model.level));
            }
            if (!string.IsNullOrEmpty(model.tags))
            {
                sb.Append(string.Format("+tags:{0}", model.tags));
            }
            sb.Append(string.Format("&limit={0}&page={1}&mode={2}&offset={3}", model.limit, model.page, model.mode, model.offset));
            if (model.starttime.HasValue || model.endtime.HasValue)
            {
                if (model.starttime.HasValue && !model.endtime.HasValue)
                {
                    model.endtime = DateTime.Now;
                }
                else
                {
                    model.starttime = default(DateTime);
                }
                sb.Append(string.Format("&time={0}-{1}", model.starttime.Value.ToString("s"), model.endtime.Value.ToString("s")));
            }
            return sb.ToString();
        }

        public BaseResponseModel WriteExceptionToExceptionless(ElpCreateExceptionReqModel model)
        {
            BaseResponseModel result = new BaseResponseModel() { IsSuccess = false, Msg = string.Empty };

            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version }, { "ProjectId", model.projectid } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.EventsApi, uriDic));

            var jsonParam = JsonHelper.SerializeObject(model);
            jsonParam = jsonParam.Replace("simple_error", "@simple_error").Replace("user", "@user");
            System.Net.HttpStatusCode code;
            string data = HttpHelper.HttpPostGetCode(apiAddress, out code, jsonParam, AuthDic);
            if (code == System.Net.HttpStatusCode.Accepted)
            {
                result.IsSuccess = true;
            }
            else
            {
                result.Msg = $"写入异常时出现错误，写入失败。得到反馈代码：{code}";
            }
            return result;
        }

        public BaseResponseModel WriteLogToExceptionless(ElpCreateLogReqModel model)
        {
            BaseResponseModel result = new BaseResponseModel() { IsSuccess = false, Msg = string.Empty };

            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version }, { "ProjectId", model.projectid } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.EventsApi, uriDic));

            var jsonParam = JsonHelper.SerializeObject(model);
            jsonParam = jsonParam.Replace("level", "@level").Replace("user", "@user");
            System.Net.HttpStatusCode code;
            string data = HttpHelper.HttpPostGetCode(apiAddress, out code, jsonParam, AuthDic);
            if (code == System.Net.HttpStatusCode.Accepted)
            {
                result.IsSuccess = true;
            }
            else
            {
                result.Msg = $"写入日志时出现错误，写入失败。得到反馈代码：{code}";
            }
            return result;
        }


        public ResponseModel<TokenModel> LoginEpl(EplLoginModel model)
        {
            var result = new ResponseModel<TokenModel>() { IsSuccess = false, Msg = string.Empty};
            var uriDic = new Dictionary<string, string>() { { "Version", _logConfig.Version }, {"ApiKey",model.AppKey } };
            var apiAddress = string.Format(@"{0}{1}", _logConfig.ServerAddress, HttpHelper.AnalysisApiAddress(_logConfig.LoginApi, uriDic));
            var jsonParam = JsonHelper.SerializeObject(model);
            System.Net.HttpStatusCode code;
            string data = HttpHelper.HttpPostGetCode(apiAddress, out code, jsonParam, null);
            if (code == System.Net.HttpStatusCode.OK)
            {
                result.IsSuccess = true;
                result.Data = JsonHelper.DeserializeObject<TokenModel>(data);
            }
            else
            {
                result.Msg = $"登录项目时出现错误，登录失败。得到反馈代码：{code}";
            }
            return result;
        }


    }
}
